package com.frain.springcloud.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.frain.springcloud.common.RequestHelper;
import com.frain.springcloud.common.XStreamUtil;
import com.frain.springcloud.face.entity.FaceResponseEntity;
import com.frain.springcloud.face.util.FaceUtil;
import com.frain.springcloud.response.message.ResponseTextMessage;
import com.frain.springcloud.tuling.util.TulingUtil;
import com.frain.springcloud.util.SignUtil;

@RestController
@RequestMapping("/weixin")
public class CustomerController {

    protected static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public void getIndex(HttpServletRequest request, HttpServletResponse response) throws IOException {

        logger.info("CustomerController getIndex.。。。。。start..");
        System.out.println("index");

        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        logger.info(
                "signature: " + signature + "   timestamp=" + timestamp + " nonce=" + nonce + "  echostr= " + echostr);

        PrintWriter writer = response.getWriter();
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            writer.write(echostr);
            writer.flush();
        }

        writer.close();

        writer = null;

        logger.info("CustomerController getIndex.。。。。。end..");
    }

    @RequestMapping(value = "/index", method = RequestMethod.POST)
    @ResponseBody
    public String autoReturnMessage(HttpServletRequest request) {

        Map<String, String> map = RequestHelper.getParamMapFromXml(request);

        // 开发者微信号
        String toUserName = map.get("ToUserName");

        // 发送方帐号（一个OpenID）
        String fromUserName = map.get("FromUserName");

        // 消息创建时间 （整型）
        String createTime = map.get("CreateTime");

        // text
        String msgType = map.get("MsgType");

        //
        String contentFinally = "";
        if ("text".equals(msgType)) {
            // 文本消息内容
            String content = map.get("Content");
            contentFinally = content.equals("a") ? "xuyaoping"
                    : content.equals("b") ? "zhuhaiyan"
                            : content.equals("c") ? "xuyunxi"
                                    : content.equals("d") ? "xuzirui"
                                            : content.equals("e") ? "hello myfamily" : TulingUtil.sendText(content);
        } else if ("image".equals(msgType)) {
            String picUrl = map.get("PicUrl");
            logger.info("图片类型消息获取图片地址=" + picUrl);
            contentFinally = JSONObject.parseObject(FaceUtil.resolveImageByWeiXinUrl(picUrl), FaceResponseEntity.class)
                    .getImage_id();
            logger.info("图片类型消息获取图片信息=" + contentFinally);
        }

        // 消息id，64位整型
        String msgId = map.get("MsgId");

        logger.info("获取到公众号返回的内容信息  toUserName=" + toUserName + "  fromUserName= " + fromUserName + "   createTime ="
                + createTime + "   msgType=" + msgType + "  content=" + contentFinally + "  msgId=" + msgId);

        logger.info("进入公众后返回值阶段");

        ResponseTextMessage message = new ResponseTextMessage();
        message.setContent(
                StringUtils.isNoneBlank(contentFinally) ? contentFinally : "xuyaoping-zhuhaiyan-xuyunxi-xuzirui");

        message.setCreateTime(System.currentTimeMillis());

        message.setFromUserName(toUserName);

        message.setMsgType("text");

        message.setToUserName(fromUserName);

        String xml = XStreamUtil.textMessagToXml(message);
        logger.info("信息转成xml的值为:" + xml);
        return xml;
    }

    @RequestMapping("/test")
    @ResponseBody
    public String getTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("test");

        Map<String, Object> paramMap = RequestHelper.getParamMap(request);

        logger.info("CustomerController getTest.。。。。。begin.paramMap=." + paramMap);
        logger.info("CustomerController getTest.。。。。。ip=." + request.getRemoteAddr());
        System.out.println(request.getRemoteAddr());
        logger.info("CustomerController getTest.。。。。。begin..");
        return "test";
    }

}
